package com.gopay.checkorder.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.BosConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.bos.ebank.BosB2cMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.BankInteractRemoteService;
/**
 * @CheckOrderBosB2cImpl.java
 * @author LiLiLi
 */
public class CheckOrderBosB2cImpl implements BankOrderService {
	private final static Logger logger = LoggerFactory.getLogger("BOS");

	@Resource(name = "bankClient")
	private BankInteractRemoteService bankClient;
	
	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		CheckOrderResult checkOrderResult = new CheckOrderResult();
		checkOrderResult.setSuccess(false);
		checkOrderResult.setOrderId(bankOrder.getOrderId());
		try {
			BosB2cMessage base = new BosB2cMessage();
			base.setOrderId(bankOrder.getOrderId());
			base.setBankOrderId(bankOrder.getOutOrderId());
			base.setBank(BankConstants.BANK_LOGO_BOS);
			base.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
			base.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
			base.setOrderList(bankOrder.getOutOrderId());
			base.setOrderBeginDate(bankOrder.getSendBankTm().toString());
			base.setOrderEndDate(bankOrder.getSendBankTm().toString());
			Result result = new Result();

			result = bankClient.query(base);

			if (result == null || !result.isSuccess()) {
				logger.error("bankClient fail.");
				if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
					BankCountDownLatch.failIncrease(bankOrder.getBankCode());
					checkOrderResult.setCommunicateError(true);
				}
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("系统返回对账结果为空");
				return checkOrderResult;
			}
			BosB2cMessage res = (BosB2cMessage) result.getDefaultModel();
			if (res == null) {
				// 查询订单为空
				logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + ProcCodeConstants.PROC_CODE_100E6022+ " err:bis query is null.");
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
				checkOrderResult.setErrMsg("银行返回对账结果为空");
				return checkOrderResult;
			}
			String returnCode = res.getRetCode(); // 订单查询交易返回码
			String retMsg = res.getErrMsg(); // 订单查询交易信息
			if (returnCode != null && !returnCode.equals(BosConstants.ORDER_RET_CODE_SUCCESS)) {
				// 查询订单错误
				logger.error("fail:orderId:" + bankOrder.getOrderId()+ " errcode:" + returnCode + " err:" + retMsg);
				checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
				checkOrderResult.setErrMsg(retMsg);
				return checkOrderResult;
			}
			String orderStatus = res.getOrdersResults();// 订单状态
			//成功处理
			if (orderStatus != null && !orderStatus.equals("")) {
				if (orderStatus.equals(BosConstants.ORDER_STATUS_SUCCESS)){
					logger.error("bos return message: "+ToStringBuilder.reflectionToString(res));
					checkOrderResult.setSuccess(true);
					InAccInfo accInfo = new InAccInfo();
					accInfo.setOrderId(bankOrder.getOrderId());
					//以分为单位
					String fen =res.getMerOrderAmt();
					accInfo.setAmount(new BigDecimal(TransUtil.amountConvert2Yuan(fen)));
					accInfo.setRetCode("00");
					accInfo.setCardType(BankCardType.Unknown.toString());
					checkOrderResult.setAccInfo(accInfo);
				    logger.error("bos return accInfo: "+ToStringBuilder.reflectionToString(accInfo));
					logger.error("上海银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易成功返回信息：" + retMsg+ ",查到的订单状态:" + orderStatus);
				}
				//失败处理
				else if (orderStatus.equals(BosConstants.ORDER_STATUS_FAILURE)) {
					checkOrderResult.setBankFailure(true);
					checkOrderResult.setErrMsg("银行返回交易失败");
					logger.error("上海银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易成功返回信息：" + retMsg+ ",查到的订单状态:" + orderStatus);
				}
				//不处理
				else if (orderStatus.equals(BosConstants.ORDER_STATUS_DEALING)) {
					checkOrderResult.setErrMsg("银行返回交易处理中");					
					logger.error("上海银行B2C订单:" +  bankOrder.getOutOrderId()+ ",交易失败返回信息：" + retMsg+ ",查到的订单状态:" + orderStatus);
				} else if (orderStatus.equals(BosConstants.ORDER_STATUS_SUSPICIOUS)) {
			        checkOrderResult.setErrMsg("银行返回支付交易可疑");
					logger.error("上海银行B2C订单:" + bankOrder.getOutOrderId()+ ",交易返回信息：" + retMsg+ ",暂不进行账务处理,查到的订单状态:" + orderStatus);
				} else {
					logger.info("上海银行B2C订单" + bankOrder.getOutOrderId() + "的交易发生未明情况");
					checkOrderResult.setErrMsg("银行返回交易未明情况");
				}
			}// 没有查到订单
			else {
				logger.error(" BOS B2C orderId:" + bankOrder.getOrderId()+ ",returnMsg:  not found order");
				checkOrderResult.setErrMsg("银行返回订单未查到");
			}
			return checkOrderResult;
		} catch (Exception e) {
			logger.error("bankClient fail.", e);
			checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
			checkOrderResult.setErrMsg("银行对账异常");
			return checkOrderResult;
		}
	}

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
